﻿using Abp.Application.Services.Dto;
using Abp.Dapper.Repositories;
using Abp.Domain.Repositories;
using Abp.Runtime.Session;
using Abp.Web.Models;
using AppFramework.Authorization.Users;
using AppFramework.DinosaursParkMes.SignalR.DTo;
using AppFramework.DinosaursParkMes.SingnalrModel;
using AppFramework.DinosaursParkMes.WorkOrder;
using AppFramework.SignalR;
using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;
using NUglify.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AppFramework.DinosaursParkMes.SignalR
{
    [DontWrapResult]
    public class AnnouncementAppService : AppFrameworkAppServiceBase, IAnnouncementAppService
    {
        private readonly IRepository<Announcement> repository;
        private readonly IRepository<UserInfo> repositoryInfo;
        private readonly IWorkOrderAppService workOrderApp;
        private readonly IRepository<User,long> repositoryUser;
        private readonly IAbpSession abpSession;
        private readonly IHubContext<MessageHub> hubContext;
        private readonly IDapperRepository<UserInfo> dapper;

        public AnnouncementAppService(IRepository<Announcement> repository, IRepository<UserInfo> repositoryInfo, IWorkOrderAppService workOrderApp, IRepository<User, long> repositoryUser, IAbpSession abpSession, IHubContext<MessageHub> hubContext,IDapperRepository<UserInfo> dapper=null)
        {
            this.repository = repository;
            this.repositoryInfo = repositoryInfo;
            this.workOrderApp = workOrderApp;
            this.repositoryUser = repositoryUser;
            this.abpSession = abpSession;
            this.hubContext = hubContext;
            this.dapper = dapper;
        }
        /// <summary>
        /// 查看公告详细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ResponseAnnounDTO> GetFindId(int id)
        {
            var query = repositoryInfo.GetAll().Where(x => x.Id == id).FirstOrDefault();
            query.Readunread = true;
            repositoryInfo.Update(query);
            Announcement announcement = repository.GetAll().Where(x => x.Serialnumber == query.Serialnumber).FirstOrDefault();
            var tity = ObjectMapper.Map<ResponseAnnounDTO>(announcement);

            return tity;

        }

        /// <summary>
        /// 记录未读条数
        /// </summary>
        /// <returns></returns>
        public async Task<int> GetCount()
        {
            string sql = "select a.Userid,count(1) as number from UserInfos as a where a.IsDeleted='false' and a.Readunread='false' group by a.Userid";
            var query = dapper.Query<UserNumber>(sql);
            var entity = query.Where(x => x.Userid == 1).FirstOrDefault();
            return entity.number;
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="dto"></param>
        public async Task<PagedResultDto<ResponseAnnounDTO>> GetNotificationaaaaaaa(InquireDTO dto)
        {
            PagedResultDto<ResponseAnnounDTO> result = new PagedResultDto<ResponseAnnounDTO>();
            List<ResponseAnnounDTO> list = new List<ResponseAnnounDTO>();
            var query = repositoryInfo.GetAll().Where(x => x.Readunread == false && x.Userid == 1 && x.IsDeleted == false);
            query.ToList().ForEach(x =>
            {
                var entity = repository.GetAll().Where(z => z.Serialnumber == x.Serialnumber);
                var name=entity.FirstOrDefault();
                list.Add(new ResponseAnnounDTO { Titlename =name.Titlename, Id = x.Id, Issuetime = x.Createdate });
            });
            result.Items = list.OrderByDescending(y => y.Issuetime).Skip((dto.pageindex - 1) * dto.pagesize).Take(dto.pagesize).ToList();
            result.TotalCount = list.Count;
            return result;
        }
        /// <summary>
        /// 公告显示
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<PagedResultDto<AnnouncementDto>> GetShow(InquireDTO dto)
        {
            PagedResultDto<AnnouncementDto> restult = new PagedResultDto<AnnouncementDto>();
            var list = from x in repository.GetAll() 
                       where x.IsDeleted == false
                       select new AnnouncementDto
                       {
                           Id = x.Id,
                           Titlename= x.Titlename,
                           Content= x.Content,
                           Issuer= x.Issuer,
                           Issuetime= x.Issuetime,
                           State= x.State,
                       };
            if (!string.IsNullOrEmpty(dto.Titlename))
            {
                list = list.Where(x => x.Titlename.Equals(dto.Titlename));
            }
            if (!string.IsNullOrEmpty(dto.Issuer))
            {
                list = list.Where(x => x.Issuer.Equals(dto.Issuer));
            }
            var time = Convert.ToString(dto.Issuetime);
            if (!string.IsNullOrEmpty(time))
            {
                list = list.Where(x => x.Issuetime.Equals(dto.Issuetime));
            }
            restult.TotalCount= list.Count();
            restult.Items = await list.OrderByDescending(x => x.Issuetime).Skip((dto.pageindex - 1) * dto.pagesize).Take(dto.pagesize).ToListAsync();
            return restult;
        }
        /// <summary>
        /// 公告添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> PostCreate(RequestAnnouncementDto model)
        {
            var modelName = "Announcement";
            //给公告表赋值
            Announcement announcement = new Announcement()
            {
                Serialnumber = await workOrderApp.GetCode(modelName),
                Titlename = model.Titlename,
                Content = model.Content,
                //获取当前登录人，赋值给发布人
                Issuer = "admin",
                Issuetime = DateTime.Now.ToLocalTime()
            };

            //编号根据编号规则自动生成
            
            
           var entity= repository.Insert(announcement);
            var query = repositoryUser.GetAll().ToList();
            List<UserInfo> list = new List<UserInfo>();
            //循环获取到注册的所有用户，给所有用户发送公告
            for (int i = 0; i < query.Count(); i++)
            {
                //用户信息表赋值
                UserInfo user = new UserInfo()
                {
                    Userid= Convert.ToInt32(query[i].Id),
                    Serialnumber = announcement.Serialnumber,
                    Readunread = false,
                    Createdate= DateTime.Now.ToLocalTime(),
                };
                list.Add(repositoryInfo.Insert(user));
            }
            if(entity==null||list.Count==0)
            {
                return -1;
            }
            else
            {
                await hubContext.Clients.All.SendAsync("signalrmessage", "1");
                return 1;
            }
        }
    }
}
